import React, { Component } from 'react';
import classnames from 'classnames';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Row, Col, Modal, message } from 'antd';
import { WeaAlertPage, WeaInputSearch, WeaBrowser } from 'ecCom';
import { WeaTableNew } from 'comsMobx';
import { renderNoData } from '../public';
import { getEMInfo } from '../../util';
import NewGroupVoting from './NewGroupVoting';
import VoteDetails from './VoteDetails';

const { confirm } = Modal;
let WeaTable = WeaTableNew.WeaTable;

@inject('groupListStore')
@observer
export default class GroupList extends Component {
  static defaultProps = {
    prefixCls: 'group-voting-list'
  }

  constructor(props) {
    super(props)
  
    this.state = {
       
    }
    this.viewVote = this.viewVote.bind(this);
  }
  

  componentWillMount() {
    const { groupListStore: { getGroupVoteList, setStoreState, groupid, isgroup }, location: { query } } = this.props;
    if (window.em) {
      em.ready(() => {
        const queryId = window.location.href.match(new RegExp("[\?\&]id=([^\&]*)(\&?)","i"));
        const that = this;
        em && em.setPageReload({
          setvalue: 1, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
          success: (res) => {
            // console.log('page', res)
          }
        });

        em.getTargetInfo({
          success: function (res) {
            // console.log('info', groupid, '111', isgroup, '222', that, '333', res)
            let params = {groupid: res.targetId, isgroup: res.targetType};
            setStoreState(params);
            getGroupVoteList(params);
          },
          fail: function (res) {
            // console.log('query.id', groupid, 'isgroup', isgroup, 'this',that, 'res',res, 'queryId',queryId)
            message.error(res.errMsg, '方法请求失败');
            const id = queryId && queryId[1];
            if (id) {
              that.viewVote(id);
            }
          }
        });
      });
    }
  }

  newGroupVoting = () => {
    const { groupListStore: { newGroupVotingStore, setStoreState } } = this.props;
    const { initiateVote } = newGroupVotingStore;
    setStoreState({newVisible: true}, initiateVote);
  }

  renderItem = (record) => {
    const { prefixCls } = this.props;
    return (
      <Row className={`${prefixCls}-item`} onClick={() => this.viewVote(record.id)}>
        <Col span={23} className={`${prefixCls}-item-info`}>
          <div className={`${prefixCls}-item-info-theme`}>
            <span className={`wea-f14 name`}>{record.votetheme}</span>
            {record.votestatusspan === '0' ? <span className='group-voting-state-ing'>进行中</span> : <span className='group-voting-state-end'>已结束</span>}
          </div>
          <div className={`${prefixCls}-item-info-creater`}>
            <span>{record.createridspan}</span>
            <span>{`${record.createdatespan} ${record.createtimespan}`}</span>
          </div>
        </Col>
        <Col span={1} className={`${prefixCls}-item-ops`}>
          <i className="icon-coms-Delete" onClick={(e) => this.deleteVote(e, record)} />
        </Col>
      </Row>
    )
  }

  getColumns = (columns) => {
    let newColumns = '';
    const { prefixCls, groupListStore: { listStore } } = this.props;
    const selectedRowKeys = toJS(listStore.selectedRowKeys);
    newColumns = columns.map(column => {
      let newColumn = column;
      if (newColumn.dataIndex === 'votetheme') {
        newColumn.render = (text, record, index) => this.renderItem(record);
        newColumn.title = (
          <div className={`${prefixCls}-list-container-list-title`}>
            <span>全选</span>
            <Button 
              type="primary"
              disabled={selectedRowKeys.length === 0} 
              onClick={() => this.handleShare(selectedRowKeys)}
            >{`分享(${selectedRowKeys.length})`}</Button>
          </div>
        )
      } else {
        newColumn.render = (text, record, index) => {
          let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
          return <div dangerouslySetInnerHTML={{ __html: valueSpan }} />
        }
      }
      return newColumn;
    });
    return newColumns;
  }

  /* 查看投票 */
  viewVote = (id) => {
    const { groupListStore } = this.props;
    const { setStoreState, viewGroupVote, listStore } = groupListStore;
    setStoreState({isShowDetail: true, voteId: id});
    viewGroupVote({votingid: id});
    listStore.tableUpdate({showCheck: false})
  } 

  /* 删除投票 */
  deleteVote = (e, record) => {
    e.stopPropagation();
    const { groupListStore } = this.props;
    const { groupchatvotedel, voteId } = groupListStore;
    const that = this;
    confirm({
      title: '确定要删除该投票吗？',
      onOk() {
        groupchatvotedel({votingid: record.id});
        if (voteId === record.id) {
          that.onCancelDetail();
        }
      }
    })
  }

  onCancelDetail = () => {
    const { groupListStore } = this.props;
    const { setStoreState, listStore } = groupListStore;
    setStoreState({ isShowDetail: false, dataInfo: {} });
    listStore.tableUpdate({showCheck: true})
  }

  handleShare = (selectedRowKeys) => {
    const { groupListStore } = this.props;
    const { groupchatvoteshare, groupid, isgroup } = groupListStore;
    confirm({
      title: '确定要分享所选投票吗？',
      onOk() {
        groupchatvoteshare({votingid: selectedRowKeys.join(), isgroup, groupid })
      }
    })
  }
  
  render() {
    const { prefixCls, groupListStore } = this.props;
    const { listStore, isShowDetail, listLoading, getGroupVoteList, setStoreState, isSearch, isgroup } = groupListStore;
    const datas = toJS(listStore).datas;
    const paginationProps = isShowDetail ? {size: 'small', showTotal: () => '', showQuickJumper: false, showSizeChanger: false} : undefined
    const listCls = classnames({
      [`${prefixCls}-list`]: true,
      'showDetail': isShowDetail,
    });
    const headerCls = classnames({
      [`${prefixCls}-list-header`]: true,
      'isgroup': isgroup
    })
    if (datas.length === 0 && !isSearch && !listLoading && isgroup) {
      return (
        <div className={prefixCls}>
          <WeaAlertPage 
            icon={<i className="icon-portal-reportform" />}
          >
            <div>暂无投票，快去发布投票吧！</div>
            {isgroup && <Button className='group-voting-publish' type="primary" onClick={this.newGroupVoting}>发布新投票</Button>}
          </WeaAlertPage>
          <NewGroupVoting prefixCls={prefixCls} />
        </div>
      )
    } else if (datas.length === 0 && !isSearch && !listLoading && !isgroup) {
      return renderNoData()
    }
    return (
      <div className={prefixCls}>
        <div className={listCls}>
          <div className={headerCls}>
            <WeaInputSearch
              placeholder={'搜索投票关键词'}
              className={`${prefixCls}-list-header-search`}
              onSearch={v => {getGroupVoteList({groupvotename: v}); setStoreState({isSearch: true})}}
            />
            {isgroup ? <Button className={`${prefixCls}-list-header-publish`} type="primary" onClick={this.newGroupVoting}>发起新投票</Button> : null}
          </div>
          <div className={`${prefixCls}-list-container`}>
            { datas.length === 0 && isSearch ? renderNoData() :
              <div className={`${prefixCls}-list-container-list`}>
                <WeaTable
                  ref='voteList'
                  comsWeaTableStore={listStore}
                  needScroll
                  getColumns={this.getColumns}
                  showHeader={!isShowDetail}
                  paginationProps={paginationProps}
                  needRowClick
                />
              </div>
            }
          </div>
        </div>
        <VoteDetails prefixCls={prefixCls} />
        <NewGroupVoting prefixCls={prefixCls} />
      </div>
    )
  }
}
